#define __PIC24F04KA200__
#include "p24F04KA200.h"
#include "adc.h"
#include "system.h"

unsigned int *buffers[] = {
    &ADC1BUF0,
    &ADC1BUF1,
    &ADC1BUF2,
    &ADC1BUF3,
    &ADC1BUF4,
    &ADC1BUF5,
    &ADC1BUF6,
    &ADC1BUF7,
    &ADC1BUF8,
    &ADC1BUF9,
    &ADC1BUFA,
    &ADC1BUFB,
    &ADC1BUFC,
    &ADC1BUFD,
    &ADC1BUFE,
    &ADC1BUFF
};

void adc_init() {

    AD1PCFG = ANALOG_PIN_CONFIG;

    AD1CHSbits.CH0NA = 0;

    AD1CON3bits.ADCS = 0b001111;
    AD1CON3bits.SAMC = 10;
    AD1CON3bits.ADRC = 0;

    AD1CON2bits.ALTS = 0;
    AD1CON2bits.BUFM = 0;
    AD1CON2bits.SMPI = 0b0000;
    AD1CON2bits.CSCNA = 0;
    AD1CON2bits.OFFCAL = 0;
    AD1CON2bits.VCFG = 0b000;

    AD1CON1bits.ASAM = 0;
    AD1CON1bits.SSRC = 0;
    AD1CON1bits.FORM = 0;
    AD1CON1bits.ADSIDL = 0;
    AD1CON1bits.ADON = 1;
}

unsigned adc_convert(unsigned input) {
    unsigned i = 0;
    AD1CHSbits.CH0SA = input;

    AD1CON1bits.SAMP = 1;
    for (i = 0; i < 50; i++);
    AD1CON1bits.SAMP = 0;

    while (!AD1CON1bits.DONE);

    return *(buffers[input]);
}